﻿using System;
using System.Collections.Generic;
using System.Linq;
using Contracts.Entities;
using NLog;
using System.Data.Objects;

namespace Model.Movie
{
    public class ReadMovieItemsLookup
    {
        protected Logger logger = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// Lesen aller MovieItems
        /// </summary>
        public void Process()
        {
            logger.Debug("Read Movies");

            /// Entities für jeden Zugriff einzeln erzeugen, da sonst beim lesen auf veraltete Instanz zugegriffen werden kann
            var entities = new MovieDatabaseEntities();
            var results = new List<MovieItem>();

            foreach (var movie in entities.Movies)
            {
                results.Add(MovieItemConverter.GetLookupItem(movie));
            }
            
            OnCompleted(results);
        }

        public void Process(MovieElement element)
        {
            /// Entities für jeden Zugriff einzeln erzeugen, da sonst beim lesen auf veraltete Instanz zugegriffen werden kann
            var entities = new MovieDatabaseEntities();
            IEnumerable<MovieItem> results = new List<MovieItem>();

            try
            {
                logger.Debug("Try Read Movies for {0} {1}", element.Type.ToString(), element);

                switch (element.Type)
                {
                    case MovieElementType.Actor: results = MovieItemConverter.GetLookupItems(entities.Actors.FirstOrDefault(m => m.Id == element.Id).Movies); break;
                    case MovieElementType.Director: results = MovieItemConverter.GetLookupItems(entities.Directors.FirstOrDefault(m => m.Id == element.Id).Movies); break;
                    case MovieElementType.Country: results = MovieItemConverter.GetLookupItems(entities.Countries.FirstOrDefault(m => m.Id == element.Id).Movies); break;
                    case MovieElementType.Genre: results = MovieItemConverter.GetLookupItems(entities.Genres.FirstOrDefault(m => m.Id == element.Id).Movies); break;
                    case MovieElementType.Studio: results = MovieItemConverter.GetLookupItems(entities.Studios.FirstOrDefault(m => m.Id == element.Id).Movies); break;
                }
            }
            catch (Exception exc)
            {
                logger.Error(exc.Message);
            }
            finally
            {
                OnCompleted(results);
            }     
        }

        public event Action<IEnumerable<MovieItem>> OnCompleted = delegate { };

    }
}
